package com.mask.lego.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mask.lego.auth.feign.MemberFeignService;
import com.mask.lego.auth.vo.SocialUser;
import com.mask.lego.common.constant.AuthConstant;
import com.mask.lego.common.utils.HttpUtils;
import com.mask.lego.common.utils.R;
import com.mask.lego.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

/**
 * 社交登录
 * @author hx
 * @since 2022/1/4 9:40 下午
 */

@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/callback/weibo/response")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        String url = "https://api.weibo.com/oauth2/access_token?client_id=3926730220&client_secret=fb057e439f7fbc05b18466048a69343b&grant_type=authorization_code&redirect_uri=http://auth.lego.com/callback/weibo/response&code=" +code;
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = httpClient.execute(httpPost);
        //2、处理
        if (response.getStatusLine().getStatusCode()==200){
            //获取到accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道当前是哪个社交用户登录成功
            //1、当前用户如果是第一次进网站，就自动注册进来（为当前社交用户生成一个会员信息账号,以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            R r = memberFeignService.oauth2Login(socialUser);
            if (r.getCode()==0){
                MemberRespVo memberRespVo = r.getData(new TypeReference<MemberRespVo>() {});
                //TODO 1、默认发的令牌 session=dadas,作用域只是当前域，（解决子域与父域session共享问题）
                //TODO 2、使用json的序列化方式来序列化对象数据到redis中
                session.setAttribute(AuthConstant.SESSION_LOGIN_KEY,memberRespVo);
                //2、登录成功就跳回首页
                log.info("微博用户{}登录成功",memberRespVo.getNickname());
                return "redirect:http://lego.com";
            }else {
                return "redirect:http://auth.lego.com/login.html";
            }

        }else{
            return "redirect:http://auth.lego.com/login.html";
        }

    }



//    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
//        Map<String,String> header = new HashMap<>();
//        Map<String,String> query = new HashMap<>();
//        Map<String,String> map = new HashMap<>();
//        map.put("client_id","3926730220");
//        map.put("client_secret","fb057e439f7fbc05b18466048a69343b");
//        map.put("grant_type","authorization_code");
//        map.put("redirect_uri","http://auth.lego.com/callback/weibo/response");
//        map.put("code",code);
//        //1.根据code换取accessToken
//        HttpResponse response = HttpUtils.doPost("https://api.weibo.com",
//                "/oauth2/access_token",
//                "POST",
//                header,
//                query,
//                map);
//        if (response.getStatusLine().getStatusCode() == 200) {
//            String json = EntityUtils.toString(response.getEntity());
//            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
//            System.out.println(socialUser);
//        }else {
//            return "redirect:http://auth.lego.com/login.html";
//        }
//
//        return "redirect:http://lego.com";
//
//    }
}
